# -*- coding: utf-8 -*-
# 第一行必须有，否则报中文字符非ascii码错误
import urllib.parse as parse
import hashlib
import requests
import json

ak = 'odHssm3f6phakAAZ0oTCdYrCRA9RvyXY'
sk = '3yCMoQVH6GyaCSA8miyWkFmi6e16pl4E'


def sn_gen(queryStr):
    global ak, sn
    # 以get请求为例http://api.map.baidu.com/geocoder/v2/?address=深圳讯美科技广场&output=json&ak=yourak

    # 对queryStr进行转码，safe内的保留字符不转换
    encodedStr = parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
    # 在最后直接追加上yoursk
    rawStr = encodedStr + sk
    # md5计算出的sn值7de5a22212ffaa9e326444c75a58f9a0
    # 最终合法请求url是http://api.map.baidu.com/geocoder/v2/?address=深圳讯美科技广场&output=json&ak=yourak&sn=7de5a22212ffaa9e326444c75a58f9a0
    sn = hashlib.md5(parse.quote_plus(rawStr).encode('utf8')).hexdigest()
    return sn


querystr_get_latlng = '/geocoder/v2/?address=深圳讯美科技广场&output=json&ak={}'.format(ak)
res = requests.get("http://api.map.baidu.com/geocoder/v2/?address=深圳讯美科技广场&output=json&ak={}&sn={}".format(ak, sn_gen(querystr_get_latlng)))

print(res.text)
location = json.loads(res.text)["result"]["location"]
location = str(location['lng']) + "," + str(location['lat'])
querystr_get_addr = '/geocoder/v2/?callback=renderReverse&location={}&output=json&pois=1&ak={}'.format(location, ak)
re = requests.get("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location={}&output=json&pois=1&ak={}&sn={}".format(location, ak, sn_gen(querystr_get_addr)))
re2 = requests.get("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location={}&output=json&pois=1&ak={}".format(location, ak))
print(re.text)
print(re2.text)

# http://api.map.baidu.com/geocoder/v2/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation
#
# http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=35.658651,139.745415&output=json&pois=1&ak=您的ak //GET请求